package com.ziyun.erp.web.modules.userRegisterSource.controller;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.service.cache.constants.CachePrefix;
import com.service.cache.constants.RegionPrefix;
import com.service.cache.core.CacheService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.promotion.entity.PromotionPolicyConfigEntity;
import com.ziyun.erp.modules.promotion.service.PromotionPolicyConfigService;
import com.ziyun.erp.modules.userRegisterSource.entity.UserRegisterSourceEntity;
import com.ziyun.erp.modules.userRegisterSource.service.UserRegisterSourceService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * 注册渠道来源
 *
 * @author 'lu'
 * @email
 * @date 2018-10-11 13:44:57
 */
@RestController
@RequestMapping("userRegisterSource/userregistersource")
public class UserRegisterSourceController {
    @Autowired
    private UserRegisterSourceService userRegisterSourceService;

    @Autowired
    private PromotionPolicyConfigService promotionPolicyConfigService;
    @Autowired
    private CacheService cacheService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("userRegisterSource:userregistersource:list")
    public R list(@RequestBody Map<String, Object> params) {
        PageUtils page = userRegisterSourceService.queryPage(params);
        List<PromotionPolicyConfigEntity> couponList = promotionPolicyConfigService.selectList(new EntityWrapper<PromotionPolicyConfigEntity>()
                .eq("policy_type", "coupon")
                .eq("disabled", 0));
        Map<String, Object> couponMap = new HashMap<>();
        couponMap.put("couponList", couponList); //优惠券信息
        return R.ok().put("page", page).put("couponList", couponMap);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{sourceId}")
    @RequiresPermissions("userRegisterSource:userregistersource:info")
    public R info(@PathVariable("sourceId") Integer sourceId) {
        UserRegisterSourceEntity userRegisterSource = userRegisterSourceService.selectById(sourceId);
//        String order = userRegisterSource.getOrderCouponIds();
//        String register = userRegisterSource.getRegisterCouponIds();
//        String[] orderCouponIds = null;
//        String[] registerCouponIds = null;
//        orderCouponIds = convertStrToArray(order);
//        registerCouponIds = convertStrToArray(register);
        return R.ok().put("userRegisterSource", userRegisterSource);
//                .put("orderCouponIds", orderCouponIds).put("registerCouponIds", registerCouponIds);
    }

    /*
     * 拆分字符为"," ,然后把结果交给数组strArray
     */
    private String[] convertStrToArray(String str) {
        String[] strs = null;
        if (!StringUtils.isBlank(str)) {
            strs = str.split(","); //拆分字符为"," ,然后把结果交给数组strArray
            return strs;
        } else {
            return new String[0];
        }

    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("userRegisterSource:userregistersource:save")
    public R save(@RequestBody UserRegisterSourceEntity userRegisterSource) {
        userRegisterSource.setCreateName("" + UserUtils.getCurentUser().getUsername());
        String sourceUrl = userRegisterSource.getSourceUrl();
        String sourceKey = userRegisterSource.getSourceKey();
        String sourceName = userRegisterSource.getSourceName();
        String reg = "?tlink=";
        int count = userRegisterSourceService.selectCount(new EntityWrapper<>(new UserRegisterSourceEntity())
                .eq("source_name", sourceName));
        if (count > 0) {
            return R.error("渠道名称或渠道Key已存在");
        }
        if (sourceUrl.indexOf(reg) != -1) {
            sourceUrl = userRegisterSource.getSourceUrl();
        } else {
            sourceUrl = sourceUrl + reg + sourceKey;
        }
        userRegisterSource.setSourceUrl(sourceUrl);//拼接sourceUrl字段
        userRegisterSourceService.insert(userRegisterSource);
        cacheService.removeFromCache(CachePrefix.registerSource, RegionPrefix.one_day);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("userRegisterSource:userregistersource:update")
    public R update(@RequestBody UserRegisterSourceEntity userRegisterSource) {
        userRegisterSource.setCreateName("" + UserUtils.getCurentUser().getUsername());
        String sourceUrl = userRegisterSource.getSourceUrl();
        String sourceKey = userRegisterSource.getSourceKey();
        Boolean sedCoupon = userRegisterSource.getSendCoupon();
        String orderCouponIds = userRegisterSource.getOrderCouponIds();
        String registerCouponIds = userRegisterSource.getRegisterCouponIds();
        String reg = "?tlink=";
        if (sourceUrl.indexOf(reg) != -1) {
            sourceUrl = userRegisterSource.getSourceUrl();
        } else {
            sourceUrl = sourceUrl + reg + sourceKey;
        }
        if (orderCouponIds.equals("") && registerCouponIds.equals("")) {
            userRegisterSource.setOrderCouponIds("");
            userRegisterSource.setRegisterCouponIds("");
        }
        if (sedCoupon == false) {
            userRegisterSource.setOrderCouponIds("");
            userRegisterSource.setRegisterCouponIds("");
            userRegisterSource.setStartTime(null);
            userRegisterSource.setEndTime(null);
        }
        userRegisterSource.setSourceUrl(sourceUrl);//拼接sourceUrl字段
        userRegisterSourceService.updateByMap(userRegisterSource);//全部更新
        cacheService.removeFromCache(CachePrefix.registerSource, RegionPrefix.one_day);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("userRegisterSource:userregistersource:delete")
    public R delete(@RequestParam("sourceId") String sourceId) {
        userRegisterSourceService.deleteUpdate(sourceId);

        return R.ok();
    }

}
